Orchestrazione Master (Architettura Profonda V2)

工作流概述

这是一个包含0个节点的未知工作流,主要用于自动化处理各种任务。

工作流源代码

下载
{
  "name": "Pyragogy AI Village - Orchestrazione Master (Architettura Profonda V2)",
  "nodes": [
    {
      "parameters": {},
      "name": "Start",
      "type": "n8n-nodes-base.start",
      "typeVersion": 1,
      "position": [
        50,
        300
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "pyragogy/process",
        "options": {}
      },
      "name": "Webhook Trigger",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        250,
        300
      ],
      "webhookId": "pyragogy-master-trigger"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT 1; -- Verifica connessione DB",
        "options": {}
      },
      "name": "Check DB Connection",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        450,
        300
      ],
      "credentials": {
        "postgres": {
          "id": "pyragogy-postgres",
          "name": "Postgres Pyragogy DB"
        }
      }
    },
    {
      "parameters": {
        "authentication": "apiKey",
        "resource": "chat",
        "model": "gpt-4o",
        "messages": [
          {
            "role": "system",
            "content": "You are the Meta-orchestrator of the Pyragogy AI Village. Your task is to analyze the input and determine the optimal agent sequence for processing. Consider the input type, complexity, and goals. Available agents: Summarizer, Synthesizer, Peer Reviewer, Sensemaking Agent, Prompt Engineer, Onboarding/Explainer, Archivist. Return a JSON array of agent names in the order they should run, e.g., [\"Summarizer\", \"Synthesizer\", \"Peer Reviewer\", \"Archivist\"]. Include \"Archivist\" last if persistence is needed."
          },
          {
            "role": "user",
            "content": "Input Data:
{{ JSON.stringify($json.body) }}"
          }
        ],
        "options": {
          "response_format": {
            "type": "json_object"
          }
        }
      },
      "name": "Meta-Orchestrator",
      "type": "n8n-nodes-base.openAi",
      "typeVersion": 1,
      "position": [
        650,
        300
      ],
      "credentials": {
        "openAiApi": {
          "id": "pyragogy-openai",
          "name": "OpenAI Pyragogy"
        }
      }
    },
    {
      "parameters": {
        "functionCode": "// Analizza il piano di orchestrazione e imposta per il looping
let rawPlan = $json.choices[0].message.content;
let plan;

try {
  plan = JSON.parse(rawPlan);
} catch (e) {
  // Se il parsing fallisce, assumi che sia una stringa di array grezza
  plan = rawPlan;
}

// Estrai in modo sicuro la sequenza degli agenti:
// Se 'plan' è un oggetto e ha una chiave 'agents', usala.
// Altrimenti, se 'plan' è un array, usalo direttamente.
// Altrimenti, predefinisci un array vuoto.
const agentSequence = Array.isArray(plan) ? plan : (plan && plan.agents && Array.isArray(plan.agents) ? plan.agents : []);

// Memorizza la sequenza e l'indice corrente per il loop
$workflow.agentSequence = agentSequence;
$workflow.currentAgentIndex = 0;
$workflow.redraftLoopCount = 0; // Inizializza il contatore dei cicli di rielaborazione

// Passa i dati di input al primo agente, assicurandosi che $items[0].json.body esista
const initialInput = $items[0] && $items[0].json && $items[0].json.body ? $items[0].json.body : {};

return [{ json: { ...initialInput, agentToRun: agentSequence[0] || null } }];"
      },
      "name": "Parse Orchestration Plan",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        850,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $workflow.currentAgentIndex < $workflow.agentSequence.length }}",
              "value2": true
            }
          ]
        }
      },
      "name": "More Agents to Run?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1050,
        300
      ]
    },
    {
      "parameters": {
        "functionCode": "// Ottieni il nome dell'agente corrente
const agentName = $workflow.agentSequence[$workflow.currentAgentIndex];

// Prepara i dati per l'esecuzione dell'agente
// Passa l'output del passo precedente (o l'input iniziale).
// Se stiamo rielaborando, l'input dell'agente dovrebbe includere il feedback di rielaborazione.
const previousOutput = $json.output || $json.body.input; // Assumendo che l'output dell'agente sia memorizzato nella chiave 'output'
const agentInput = $json.redraftInput || previousOutput; // Usa redraftInput se presente, altrimenti previousOutput

return [{ json: { ...$json, agentToRun: agentName, agentInput: agentInput } }];"
      },
      "name": "Prepare Agent Input",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1250,
        200
      ]
    },
    {
      "parameters": {
        "mode": "json",
        "value": "={{ $json.agentToRun }}",
        "conditions": [
          {
            "value": "Summarizer",
            "type": "string"
          },
          {
            "value": "Synthesizer",
            "type": "string"
          },
          {
            "value": "Peer Reviewer",
            "type": "string"
          },
          {
            "value": "Sensemaking Agent",
            "type": "string"
          },
          {
            "value": "Prompt Engineer",
            "type": "string"
          },
          {
            "value": "Onboarding/Explainer",
            "type": "string"
          },
          {
            "value": "Archivist",
            "type": "string"
          }
        ]
      },
      "name": "Route Agents with Switch",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 1,
      "position": [
        1450,
        200
      ]
    },
    {
      "parameters": {
        "authentication": "apiKey",
        "resource": "chat",
        "model": "gpt-4o",
        "messages": [
          {
            "role": "system",
            "content": "You are the Summarizer Agent. Summarize the provided text into 3 key points."
          },
          {
            "role": "user",
            "content": "Text to summarize:
{{ $json.agentInput }}"
          }
        ],
        "options": {}
      },
      "name": "Summarizer Agent",
      "type": "n8n-nodes-base.openAi",
      "typeVersion": 1,
      "position": [
        1650,
        0
      ],
      "credentials": {
        "openAiApi": {
          "id": "pyragogy-openai",
          "name": "OpenAI Pyragogy"
        }
      }
    },
    {
      "parameters": {
        "authentication": "apiKey",
        "resource": "chat",
        "model": "gpt-4o",
        "messages": [
          {
            "role": "system",
            "content": "You are the Synthesizer Agent. Synthesize a creative new text from the given key points or input. If provided with 'redraft_feedback', incorporate it to refine the output."
          },
          {
            "role": "user",
            "content": "Input for synthesis:
{{ $json.agentInput }}

{{ $json.redraftFeedback ? 'Feedback per la rielaborazione: ' + $json.redraftFeedback : '' }}"
          }
        ],
        "options": {}
      },
      "name": "Synthesizer Agent",
      "type": "n8n-nodes-base.openAi",
      "typeVersion": 1,
      "position": [
        1650,
        100
      ],
      "credentials": {
        "openAiApi": {
          "id": "pyragogy-openai",
          "name": "OpenAI Pyragogy"
        }
      }
    },
    {
      "parameters": {
        "authentication": "apiKey",
        "resource": "chat",
        "model": "gpt-4o",
        "messages": [
          {
            "role": "system",
            "content": "You are the Peer Reviewer Agent. Review the provided text, highlight strengths, weaknesses, and provide actionable suggestions for improvement. In your JSON output, include a 'major_issue' boolean flag (true if significant redrafting is needed, false otherwise)."
          },
          {
            "role": "user",
            "content": "Text to review:
{{ $json.agentInput }}"
          }
        ],
        "options": {
          "response_format": {
            "type": "json_object"
          }
        }
      },
      "name": "Peer Reviewer Agent",
      "type": "n8n-nodes-base.openAi",
      "typeVersion": 1,
      "position": [
        1650,
        200
      ],
      "credentials": {
        "openAiApi": {
          "id": "pyragogy-openai",
          "name": "OpenAI Pyragogy"
        }
      }
    },
    {
      "parameters": {
        "authentication": "apiKey",
        "resource": "chat",
        "model": "gpt-4o",
        "messages": [
          {
            "role": "system",
            "content": "You are the Sensemaking Agent. Analyze the input, connect it with existing knowledge (context provided), identify patterns, gaps, and suggest new directions. In your JSON output, include a 'major_issue' boolean flag (true if significant redrafting is needed, false otherwise)."
          },
          {
            "role": "user",
            "content": "Input to analyze:
{{ $json.agentInput }}

Context from DB (if available):
{{ $json.dbContext }}"
          }
        ],
        "options": {
          "response_format": {
            "type": "json_object"
          }
        }
      },
      "name": "Sensemaking Agent",
      "type": "n8n-nodes-base.openAi",
      "typeVersion": 1,
      "position": [
        1650,
        300
      ],
      "credentials": {
        "openAiApi": {
          "id": "pyragogy-openai",
          "name": "OpenAI Pyragogy"
        }
      }
    },
    {
      "parameters": {
        "authentication": "apiKey",
        "resource": "chat",
        "model": "gpt-4o",
        "messages": [
          {
            "role": "system",
            "content": "You are the Prompt Engineer Agent. Analyze the current task context and the next agent in the sequence. Refine or generate an optimal prompt for the next agent. In your JSON output, include a 'major_issue' boolean flag (true if significant redrafting is needed, false otherwise)."
          },
          {
            "role": "user",
            "content": "Current context:
{{ JSON.stringify($json) }}
Next agent: {{ $workflow.agentSequence[$workflow.currentAgentIndex + 1] || 'None' }}"
          }
        ],
        "options": {
          "response_format": {
            "type": "json_object"
          }
        }
      },
      "name": "Prompt Engineer Agent",
      "type": "n8n-nodes-base.openAi",
      "typeVersion": 1,
      "position": [
        1650,
        400
      ],
      "credentials": {
        "openAiApi": {
          "id": "pyragogy-openai",
          "name": "OpenAI Pyragogy"
        }
      }
    },
    {
      "parameters": {
        "authentication": "apiKey",
        "resource": "chat",
        "model": "gpt-4o",
        "messages": [
          {
            "role": "system",
            "content": "You are the Onboarding/Explainer Agent. Explain the current process, the result achieved so far, or provide guidance based on the input."
          },
          {
            "role": "user",
            "content": "Explain the following:
{{ $json.agentInput }}"
          }
        ],
        "options": {}
      },
      "name": "Onboarding/Explainer Agent",
      "type": "n8n-nodes-base.openAi",
      "typeVersion": 1,
      "position": [
        1650,
        500
      ],
      "credentials": {
        "openAiApi": {
          "id": "pyragogy-openai",
          "name": "OpenAI Pyragogy"
        }
      }
    },
    {
      "parameters": {
        "functionCode": "// Prepara i metadati per il contenuto dell'Handbook.
// Assicurati che l'input originale contenga 'title' e 'tags' o imposta dei valori predefiniti.
const title = $json.body.title || 'Untitled Handbook Entry';
const tags = $json.body.tags || [];
const phase = $json.body.phase || 'draft'; // Fase iniziale, può essere 'final' dopo l'approvazione
const rhythm = $json.body.rhythm || 'on-demand'; // Ritmo cognitivo

return [{ json: { ...$json, handbookTitle: title, handbookTags: tags, handbookPhase: phase, handbookRhythm: rhythm } }];"
      },
      "name": "Add Handbook Metadata",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1650,
        600
      ]
    },
    {
      "parameters": {
        "functionCode": "// Prepara il contenuto proposto dall'Archivista per la revisione umana, inclusa la formattazione YAML.
// Assicurati che l'input dell'agente (il contenuto generato) sia disponibile.
const proposedContent = $json.agentInput;
const title = $json.handbookTitle;
const tags = $json.handbookTags;
const phase = $json.handbookPhase;
const rhythm = $json.handbookRhythm;

// Costruisci il front-matter YAML
const yamlFrontMatter = `---
title: \"${title.replace(/\"/g, '\\"')}\"
tags: [${tags.map(t => `\"${t.replace(/\"/g, '\\"')}\"`).join(', ')}]
phase: \"${phase}\"
rhythm: \"${rhythm}\"
---

`;

const finalMarkdownContent = yamlFrontMatter + proposedContent;

return [{ json: { ...$json, proposedContent: proposedContent, reviewTitle: title, reviewTags: tags, finalMarkdownContent: finalMarkdownContent } }];"
      },
      "name": "Generate Content for Review",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1850,
        600
      ]
    },
    {
      "parameters": {
        "functionCode": "// Genera un ID univoco per questa richiesta di revisione.
// Questo ID verrà usato per correlare la risposta del revisore con questa istanza del workflow.
const reviewId = crypto.randomUUID();

return [{ json: { ...$json, reviewId: reviewId } }];"
      },
      "name": "Generate Review ID",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        2050,
        600
      ]
    },
    {
      "parameters": {
        "fromEmail": "your-email@example.com",
        "toEmail": "human-reviewer@example.com",
        "subject": "Revisione Contenuto Pyragogy Handbook: {{ $json.reviewTitle }}",
        "text": "Ciao revisore,

È stato proposto un nuovo contenuto per l'Handbook:

---
{{ $json.proposedContent }}
---

Titolo: {{ $json.reviewTitle }}
Tags: {{ $json.reviewTags.join(', ') }}

Per favore, clicca su uno dei seguenti link per approvare o rifiutare:

Approva: your_n8n_url/webhook/pyragogy/review-feedback?reviewId={{ $json.reviewId }}&status=approved
Rifiuta: your_n8n_url/webhook/pyragogy/review-feedback?reviewId={{ $json.reviewId }}&status=rejected

Grazie!",
        "html": "<h3>Revisione Contenuto Pyragogy Handbook: {{ $json.reviewTitle }}</h3>
<p>Ciao revisore,</p>
<p>È stato proposto un nuovo contenuto per l'Handbook:</p>
<hr>
<pre>{{ $json.proposedContent }}

功能特点

  • 自动检测新邮件
  • AI智能内容分析
  • 自定义分类规则
  • 批量处理能力
  • 详细的处理日志

技术分析

节点类型及作用

    复杂度评估

    配置难度:
    ★☆☆☆☆
    维护难度:
    ★★☆☆☆
    扩展性:
    ★★★★☆

    实施指南

    前置条件

    • 有效的Gmail账户
    • n8n平台访问权限
    • Google API凭证
    • AI分类服务订阅

    配置步骤

    1. 在n8n中导入工作流JSON文件
    2. 配置Gmail节点的认证信息
    3. 设置AI分类器的API密钥
    4. 自定义分类规则和标签映射
    5. 测试工作流执行
    6. 配置定时触发器(可选)

    关键参数

    参数名称 默认值 说明
    maxEmails 50 单次处理的最大邮件数量
    confidenceThreshold 0.8 分类置信度阈值
    autoLabel true 是否自动添加标签

    最佳实践

    优化建议

    • 定期更新AI分类模型以提高准确性
    • 根据邮件量调整处理批次大小
    • 设置合理的分类置信度阈值
    • 定期清理过期的分类规则

    安全注意事项

    • 妥善保管API密钥和认证信息
    • 限制工作流的访问权限
    • 定期审查处理日志
    • 启用双因素认证保护Gmail账户

    性能优化

    • 使用增量处理减少重复工作
    • 缓存频繁访问的数据
    • 并行处理多个邮件分类任务
    • 监控系统资源使用情况

    故障排除

    常见问题

    邮件未被正确分类

    检查AI分类器的置信度阈值设置,适当降低阈值或更新训练数据。

    Gmail认证失败

    确认Google API凭证有效且具有正确的权限范围,重新进行OAuth授权。

    调试技巧

    • 启用详细日志记录查看每个步骤的执行情况
    • 使用测试邮件验证分类逻辑
    • 检查网络连接和API服务状态
    • 逐步执行工作流定位问题节点

    错误处理

    工作流包含以下错误处理机制:

    • 网络超时自动重试(最多3次)
    • API错误记录和告警
    • 处理失败邮件的隔离机制
    • 异常情况下的回滚操作